//
//  ByBaseVC.m
//  Private_Object
//
//  Created by pro on 16/9/18.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "ByBaseVC.h"

@interface ByBaseVC ()

@property (nonatomic, copy) NSArray *leftItemViews;
@property (nonatomic, copy) NSArray *rightItemViews;

@end

@implementation ByBaseVC

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 安装手势和动画
    [self setupAnimatorAndGesture];
    // 设置默认字体颜色
    self.tintColor = [UIColor whiteColor];
    
    // ios11以下取消vc对scroll布局的影响
    if (@available(ios 11.0,*)) {
        
    } else {
        self.automaticallyAdjustsScrollViewInsets = false;
    }
}

// ios11新增的安全区域管理回调
- (void)viewSafeAreaInsetsDidChange {
    
    [super viewSafeAreaInsetsDidChange];
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    // 设置导航栏的默认属性(默认为不透明、白色状态栏)
    [self setNaviAttributeWithTranslucent:NO stateBarLightContent:YES];
}
- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
    
    [super viewDidDisappear:animated];
}

#pragma mark - getter


#pragma mark - 转场动画 和 手势 设置，这里可以设置多种动画，使用时作不同的调用即可
- (void)setupAnimatorAndGesture {
    
    __weak typeof(self) weakself = self;
    _backCongfig = ^ {
        [weakself dismissViewControllerAnimated:YES completion:nil];
    };
    
    // 基本的转场push动画
    _normalPushAnimator = [[ByNormalPushAnimator alloc] init];
    _normalPushAnimator.toDuration = _normalPushAnimator.backDuration = 0.4;
    
    // 侧滑
    _sideslipAnimator = [[BySideslipAnimator alloc] init];
    _sideslipAnimator.toDuration = 0.3;
    _sideslipAnimator.backDuration = 0.15;
    _sideslipAnimator.backConfig = _backCongfig;
    
    // 仿淘宝详情规格选择
    _bottomPopAnimator = [[ByBottomPopAnimator alloc] init];
    _bottomPopAnimator.backConfig = _backCongfig;      
    
    // 注册返回手势
    XWInteractiveTransitionGestureDirection direction =XWInteractiveTransitionGestureDirectionRight;
    [self xw_registerBackInteractiveTransitionWithDirection:direction transitonBlock:^(CGPoint startPoint){
        
        [weakself dismissViewControllerAnimated:YES completion:nil];
    } edgeSpacing:20];

}

#pragma mark - 自定义基类方法
/** 快捷设置导航栏属性
 translucent: YES->半透明 NO->非半透明
 light:       YES->主题色 NO->黑色
 */
- (void)setNaviAttributeWithTranslucent:(BOOL)translucent
                   stateBarLightContent:(BOOL)light {
    
    // 设置状态栏
    [UIApplication sharedApplication].statusBarStyle = light ? UIStatusBarStyleLightContent : UIStatusBarStyleDefault;
    // 设置导航栏透明度
    self.navigationController.navigationBar.translucent = translucent;
    
    // 去掉导航栏背景色，用背景图代替
    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
    // 去掉导航栏下部的横线
//    self.navigationController.navigationBar.shadowImage = translucent ? [UIImage imageWithColor:[UIColor clearColor]] : [UIImage imageWithColor:[UIColor colorWithWhite:0.8 alpha:0.5]];
    self.navigationController.navigationBar.shadowImage = [UIImage imageWithColor:[UIColor clearColor]];
    // 导航栏背景图
    UIImage *bgImage = translucent ? [UIImage imageWithColor:[UIColor clearColor]] : [UIImage imageWithColor:BY_THEME_COLOR];
    [self.navigationController.navigationBar setBackgroundImage:bgImage forBarMetrics:UIBarMetricsDefault];
}


#pragma mark ********** items **********
#define kLeftItemTagBase  1000
#define kRightItemTagBase 2000
#define kItemMargin       10
// 创建导航栏返回按钮
- (void)addLeftBackBarButtonItem {
    
    [self addBYItemviews:@[@"Common_navi_back"] mode:ByNavigationItemModeImage position:ByNavigationItemPositionModeLeft];
}
// 添加自定义的控件 到左右两侧
- (void)addCustomItemviews:(NSArray *)views
                  position:(ByNavigationItemPositionMode)position {
    
    // 左侧
    if (position == ByNavigationItemPositionModeLeft) {
        
        NSMutableArray *temp = [[NSMutableArray alloc] init];
        for (UIView *leftView in views) {
            NSInteger index = [views indexOfObject:leftView];
            leftView.tag = kLeftItemTagBase + index;    // 设置tag
            
            UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftView];
            [temp addObject:leftItem];
            
        }
        self.leftItemViews = [temp copy];
        self.navigationItem.leftBarButtonItems = self.leftItemViews;
        
    }
    // 右侧
    else {
        
        NSMutableArray *temp = [[NSMutableArray alloc] init];
        for (UIView *rightView in views) {
            NSInteger index = [views indexOfObject:rightView];
            rightView.tag = kRightItemTagBase + index;    // 设置tag

            UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightView];
            [temp addObject:rightItem];
        }
        self.rightItemViews = [temp copy];
        self.navigationItem.rightBarButtonItems = self.rightItemViews;
    }
}
// 添加指定类型的 左右控件，根据mode来做不同的实现
- (void)addBYItemviews:(NSArray *)itemStrs
                  mode:(ByNavigationItemMode)mode
              position:(ByNavigationItemPositionMode)position {
    
    NSArray *views = [self createBYItems:itemStrs mode:mode position:position];
    [self addCustomItemviews:views position:position];
}
// 创建左右控件元素
- (NSArray *)createBYItems:(NSArray *)itemStrs
                      mode:(ByNavigationItemMode)mode
                  position:(ByNavigationItemPositionMode)position {

    NSMutableArray *views = [[NSMutableArray alloc] initWithCapacity:itemStrs.count];
    switch (mode) {
        case ByNavigationItemModeImage: {
            for (NSString *imageStr in itemStrs) {
                UIButton *imageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                [imageBtn setImage:[UIImage imageNamed:imageStr] forState:UIControlStateNormal];
                [imageBtn addTarget:self action:@selector(btnTap:) forControlEvents:UIControlEventTouchUpInside];
                [views addObject:imageBtn];
                imageBtn.frame = CGRectMake(0, 0, 20, 20);
            }
        }
            break;
        case ByNavigationItemModeText: {
            for (NSString *textStr in itemStrs) {
            
                UIButton *textBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                [textBtn setTitle:textStr forState:UIControlStateNormal];
                [textBtn setTitleColor:self.tintColor forState:UIControlStateNormal];
                textBtn.titleLabel.font = FONT(16);
                [textBtn addTarget:self action:@selector(btnTap:) forControlEvents:UIControlEventTouchUpInside];
                [views addObject:textBtn];
                textBtn.frame = CGRectMake(0, 0, [textStr getSizeOfString:16].width, 20);
            }
        }
            break;
        case ByNavigationItemModeImageAndText: {
            
            CGFloat margin = 5;
            for (NSString *textStr in itemStrs) {
                UIControl *mixView = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, 0, 44)];
                [mixView addTarget:self action:@selector(btnTap:) forControlEvents:UIControlEventTouchUpInside];
                // 图片
                UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
                imgView.image = [UIImage imageNamed:textStr];
                // 文字
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, [textStr getSizeOfString:12].width, 20)];
                label.font = FONT(12);
                label.text = textStr;
                label.textAlignment = NSTextAlignmentCenter;
                label.textColor = self.tintColor;
                
                [mixView addSubview:imgView];
                [mixView addSubview:label];
                
                mixView.width = MAX(imgView.width, label.width);
                
                // 设置位置
                CGFloat remainY = mixView.height - imgView.height - label.height - margin;
                imgView.top = remainY / 2;
                imgView.x = mixView.width / 2;
                label.top = imgView.bottom + margin;
                
                [views addObject:mixView];
            }
        }
            break;
            
        default:
            break;
    }
    
    return [views copy];
}

// 改变左右控件的颜色
- (void)setTintColor:(UIColor *)tintColor {
    _tintColor = tintColor;
    if (self.leftItemViews) {
        for (UIBarButtonItem *item in self.leftItemViews) {
            [self checkColorForSubviews:item.customView];
        }
    }
    if (self.rightItemViews) {
        for (UIBarButtonItem *item in self.rightItemViews) {
            [self checkColorForSubviews:item.customView];
        }
    }
}
// 检查并设置左右控件的颜色
- (void)checkColorForSubviews:(UIView *)view {
    
    if ([view isKindOfClass:[UILabel class]]) {
        UILabel *label = (UILabel *)view;
        label.textColor = _tintColor;
    } else if ([view isKindOfClass:[UIButton class]]) {
        UIButton *button = (UIButton *)view;
        [button setTitleColor:_tintColor forState:UIControlStateNormal];
    } else {
        for (UIView *subview in view.subviews) {
            [self checkColorForSubviews:subview];
        }
    }
}


#pragma mark - tap
- (void)btnTap:(UIButton *)button {
    if (button.tag >= kRightItemTagBase) {      // 点击了右侧的按钮
        [self rightItemsAction:button.tag - kRightItemTagBase];
    } else {                                    // 点击了左侧的按钮
        [self leftItemsAction:button.tag - kLeftItemTagBase];
    }
}
- (void)leftItemsAction:(NSInteger)leftIndex {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)rightItemsAction:(NSInteger)rightIndex {
    NSLog(@"** right -> 具体实现在外部实现!");
}
// push
- (void)by_normalPush:(UIViewController *)vc hasNavi:(BOOL)hasNavi {
    UIViewController *pushVC = hasNavi ? [[ByBaseNaviController alloc] initWithRootViewController:vc] : vc;
    [self xw_presentViewController:pushVC withAnimator:self.normalPushAnimator];
}

- (void)by_normalPopVC:(NSString *)vcNmme {
    
    UIView *temp = [self.navigationController.view snapshotViewAfterScreenUpdates:NO];
    UINavigationController *rootVC = (UINavigationController *)self.presentingViewController;
    
    while (rootVC.presentingViewController) {
        
        UIViewController *vc = nil;
        
        if ([rootVC isKindOfClass:[UINavigationController class]]) {
            vc = ((UINavigationController *)rootVC).viewControllers[0];
        }
        
        rootVC = (UINavigationController *)rootVC.presentingViewController;
        
        if ([vc isKindOfClass:NSClassFromString(vcNmme)]) {
            vc.title = self.title;
            vc.navigationController.navigationBar.hidden = YES;
            [vc.view addSubview:temp];
            break;
        }
    }
    
    [rootVC dismissViewControllerAnimated:YES completion:nil];
}



@end
